package test.myTest;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author Firenut
 * @Date 2023-08-14 23:30
 */
class LRUCache {
    Map<Integer, ListNode> map = new HashMap<>();
    int capacity;
    ListNode head, tail;

    public static void main(String[] args) {
        LRUCache lRUCache = new LRUCache(2);
        lRUCache.put(1, 1); // 缓存是 {1=1}
        lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
        lRUCache.get(1);    // 返回 1
        lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
        lRUCache.get(2);    // 返回 -1 (未找到)
        lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
        lRUCache.get(1);    // 返回 -1 (未找到)
        lRUCache.get(3);    // 返回 3
        lRUCache.get(4);    // 返回 4
    }

    public LRUCache(int capacity) {
        this.capacity = capacity;
        // 哑结点
        head = new ListNode();
        tail = new ListNode();
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        ListNode node = map.get(key);
        remove(node);
        addFirst(node);
        return node.val;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            ListNode node = map.get(key);
            node.val = value;
            // map.put(key,node);
            remove(node);
            addFirst(node);
        } else {
            ListNode node = new ListNode(key, value);
            addFirst(node);

            //
            if (map.size() > this.capacity) {
                // 移除最后一个结点
                ListNode del = tail.pre;
                map.remove(del);
                remove(tail.pre);
            }
        }
    }

    // 从链表中删除某个结点
    void remove(ListNode del) {
        // 从链表中移除
        del.pre.next = del.next;
        del.next.pre = del.pre;
    }

    // 在链表头部添加结点
    void addFirst(ListNode node) {
        head.next.pre = node;
        node.next = head.next;
        head.next = node;
        node.pre = head;
    }
}

// 双向链表
class ListNode {
    ListNode pre, next;
    int key;
    int val;

    ListNode() {
    }

    ListNode(int key, int val) {
        this.key = key;
        this.val = val;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */